//
//  CYCompanyUserTool.m
//  CreditAddressBook
//
//  Created by LE on 15/12/15.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYCompanyUserTool.h"
#import "CYCompanyUserData.h"
#import "CYJumpsTool.h"
#import "CYLoginHttpTool.h"

#define CYUserFile [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"companyUser.data"]

@implementation CYCompanyUserTool
/**
 *  保存用户登录信息
 */
+ (BOOL)saveUserLoginInfo:(CYCompanyUserModel *)user {
    CYCompanyUserData *userData = [[CYCompanyUserData alloc] init];
    userData.user = user;
    userData.loginInTime = [NSDate date];
    NSTimeInterval interval = 24*60*60*90;
    userData.expiresTime = [[NSDate alloc] initWithTimeIntervalSinceNow:interval];//获取90天后的日期
    BOOL result = [NSKeyedArchiver archiveRootObject:userData toFile:CYUserFile];
    if (result) {
        return YES;
    }
    return NO;
}
/**
 *  更新用户信息
 */
+ (BOOL)updateUserData:(CYCompanyUserModel *)user {
    //取出旧数据
    CYCompanyUserData *userData = [self userData];
    if (userData && user) {
        userData.user = user;
        //        CYLog(@"更新用户信息:%@", user.examineStatus);
        //序列化
        [NSKeyedArchiver archiveRootObject:userData toFile:CYUserFile];
        return YES;
    }
    return NO;
}
/**
 *  获取用户信息
 */
+ (CYCompanyUserData *)userData {
    // 取出账号
    CYCompanyUserData *account = [NSKeyedUnarchiver unarchiveObjectWithFile:CYUserFile];
    // 判断账号是否过期
    NSDate *now = [NSDate date];
    if ([now compare:account.expiresTime] == NSOrderedAscending) { // 还没有过期
        return account;
    } else { // 过期
        [self logout];
        return nil;
    }
}
/**
 *  获取用户信息
 */
+ (CYCompanyUserModel *)companyUser {
    CYCompanyUserData *userData = [self userData];
    return userData.user;
}
/**
 *  清除用户信息
 */
+ (BOOL)isClearUserData {
    NSFileManager * fileManager = [[NSFileManager alloc]init];
    if ([fileManager isDeletableFileAtPath:CYUserFile]) {
        [fileManager removeItemAtPath:CYUserFile error:nil];
        return YES;
    }
    return NO;
}

+ (BOOL)logout {
    //登出后清除本地归档信息
    BOOL result = [self isClearUserData];
    if (result) {
        return YES;
    }
    return NO;
}

+ (void)logoutWithController:(UIViewController *)con {
    [self logout];
    [CYJumpsTool jumpToCompanyLogin:con];
}

+ (void)getUserWithUseType:(CYUserType)userType user:(void(^)(CYUser *user))user companyUser:(void(^)(CYCompanyUserModel *companyUser))companyUser {
    if (userType == CYUserTypePerson) {
        CYUser *userM = [CYLoginHttpTool userData].user;
        user(userM);
    } else if (userType == CYUserTypeCompany) {
        CYCompanyUserModel *userM = [CYCompanyUserTool companyUser];
        companyUser(userM);
    }
}
@end
